var contextPath = $("#contextPath").val();
var goodsSpecList,ratioConfigure;
var goodsInfo,goodsPic;
var isSales,isPointsBuy,preview;
$(function() {
		goodsSpec = $(".goods_options");
		goodsInfo = $("#goodsInfo");
		goodsPic = $('#goods_pic');
		dataInit();
		new Compute();
});

$(document).on('click','.ui_btn_plain_primary', function() {
	var $this = $(this);
	addToCart();
});

function addToCart() {
	var specs = $('.options_box_item_active');
	var spec="";
	$.each(specs,function(i,v){
		if(i==0){
			spec = v.id;
		}else{
			spec +=','+ v.id;
		}
	});
	var amount = $(".quantity_input").val();
	var goodsId = $("#goodsId").attr("value");
	$.ajax({
		  url:contextPath+"/shoppingCart/addShopCartOne",
		  data:{goodsId:goodsId,spec:spec,buyNum:amount},
		  type:"post",
		  dataType:"json",
		  success : function(data, textStatus) {
			  var state = data.result.state;
			  if(state == 1){
				  layer.open({
					    content:'成功加入购物车',
					    time: 2
					});
				  var goodsNum = parseInt($(".quantity_tips").html());
				  $(".quantity_tips").html(goodsNum+parseInt(amount));
				  $(".quantity_tips").show();
			  }else {
				  var code = data.result.code;
				  var message = data.result.message;
				  var url = data.result.url;
					  layer.open({
						    content:message,
						    btn: ['我知道了'],
						    yes: function(index){
						    	if(url != ''){
								location.href=url;
						    	}
						    }

						});
				  
			  }
		   },
		   error : function(XMLHttpRequest, textStatus, errorThrown){
				layer.open({
				    content:textStatus,
				    time: 2
				});
			}
	  });
}
function getSpec(){
	var specs = $('.options_box_item_active');
	var spec="";
	$.each(specs,function(i,v){
		if(i==0){
			spec = v.id;
		}else{
			spec +=','+ v.id;
		}
	});
	return spec;
}

function dataInit(){
	var id = $("#goodsId").attr("value");
	$.ajax({
		url:"detail",
		data:{'id':id},
		type:"post",
		async:true,
		dataType:"json",
		success : function(data, textStatus) {
			if(data.result.state == 1){
				if(data.obj.picture != undefined){
				var pictures = data.obj.picture.split(',');
					$.each(pictures,function(i,v){
						goodsPic.append('<div class="swiper-slide"><a href="#"><img src="' + pictures[i] + '" alt=""></a></div>');
					});
				} else if(data.obj.thumb != undefined){
					goodsPic.append('<div class="swiper-slide"><a href="#"><img src="' + data.obj.thumb + '" alt=""></a></div>');
				}
				//商品图预览
				preview = new Swiper('.swiper-container', {
				  loop: true,
				  autoplay: 3000,
				  autoHeight: true,
				  pagination: '.swiper-pagination',
				  paginationClickable: true
				});
				$("#title").html(data.obj.title);
				$("#describe").html(data.obj.describe);
				
				isPointsBuy = data.obj.is_points_buy;
				if(data.obj.is_points_buy == '01'){
					$(".normal").hide();
					if( data.obj.change_price == 0){
						$(".rebate").html("<em class='npoints'>" + data.obj.change_points + "</em> 兑换券");
						$(".cost").html("原价<del class='sellPrice'>&yen;" + data.obj.real_price + "</del>");
					}else{
						$(".rebate").html("<em class='npoints'>" + data.obj.change_points + "</em> 兑换券 + <span class='money'>" + data.obj.change_price + "</span>元");
						$(".cost").html("原价<del class='sellPrice'>&yen;" + data.obj.real_price + "</del>");	
					}
					
				}else{
					$(".normal").html("&yen; " + data.obj.real_price);
					$(".rebate").hide();
					$(".cost").hide();
					if(	Number(data.obj.return_points)>0){
						$(".voucher").html('赠 <em class="n">'+data.obj.return_points+'</em>兑换券');
					}
				}

				document.getElementById("vip_tips").style.display = "none";
				
				goodsSpecList = data.goodsSpecList;
				ratioConfigure = data.ratioConfigure;
				var gl = data.rSpecType;
				if(gl!=null && gl.length>0){
					var glHtml="";
					$.each(gl,function(gli,glv){
						glHtml +='<div class="goods_options_item" id="specification">'+
								'<span class="goods_options_name">'+glv.label_name+'</span>'+
								'<div class="goods_options_box"> <div class="options_box_list">';
						$.each(glv.rSpecDetail,function(glai,glav){
							if(glai == 0){
								glHtml +='<span id='+glav.id+' class="options_box_item options_box_item_active">'+glav.attr_name+'</span>';
							}else{
								glHtml +='<span id='+glav.id+' class="options_box_item">'+glav.attr_name+'</span>';	
							}
						})
						glHtml +='</div> </div></div>';
					});
					glHtml +='<div class="goods_options_item">'+
					      '<span class="goods_options_name">数量</span>'+
					      '<div class="goods_options_box">'+
					        '<div class="options_box_list">'+
					         '<span class="quantity dib vm">'+
					               '<a class="quantity_subtract dib vm" href="javascript:;">-</a>'+
					              '<input class="quantity_input dib vm" type="text" value="1" min="0" name="">'+
					              '<a class="quantity_add dib vm" href="javascript:;">+</a>'+
					            '</span>'+
					        '</div>'+
					      '</div>'+
					   '</div>';
					goodsSpec.append(glHtml);
					 new Compute();
					isSales = data.obj.is_sales;
					var bidPrice = goodsSpecList[getSpec()].bid_price;
					var marketPrice = goodsSpecList[getSpec()].market_price;
					var price = goodsSpecList[getSpec()].price;
					var salesPrice = goodsSpecList[getSpec()].salesPrice;
					if(isPointsBuy == "01"){
						if(isSales == "00"){
							var changePoints = getReqPoints(bidPrice,marketPrice,price);
							var discount = toDecimal(bidPrice/marketPrice);
							var minRatio = ratioConfigure.min_ratio;
							var changePrice = 0;
							if(discount > minRatio){
								changePrice = (price-changePoints).toFixed(2);
							}
							if(changePrice == 0){
								$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券");
							}else{
								$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券 + <span class='money'>" + changePrice + "</span>元");
							}
							$(".sellPrice").html(price);
						}else{
							var changePoints = getReqPoints(bidPrice,marketPrice,salesPrice);
							var discount = toDecimal(bidPrice/marketPrice);
							var minRatio = ratioConfigure.min_ratio;
							var changePrice = 0;
							if(discount > minRatio){
								changePrice = (price-changePoints).toFixed(2);
							}
							if(changePrice == 0){
								$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券");
							}else{
								$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券 + <span class='money'>" + changePrice + "</span>元");
							}
							$(".sellPrice").html(salesPrice);
						}
					}else{
						if(isSales == "00"){
							$(".normal").html("&yen; " + price);
						}else{
							$(".normal").html("&yen; " + salesPrice);
						}
					}
					
				}else{
					var  buyNumHtml ='<div class="goods_options_item">'+
				      '<span class="goods_options_name">数量</span>'+
				      '<div class="goods_options_box">'+
				        '<div class="options_box_list">'+
				         '<span class="quantity dib vm">'+
				               '<a class="quantity_subtract dib vm" href="javascript:;">-</a>'+
				              '<input class="quantity_input dib vm" type="text" value="1" min="0" name="">'+
				              '<a class="quantity_add dib vm" href="javascript:;">+</a>'+
				            '</span>'+
				        '</div>'+
				      '</div>'+
				   '</div>';
				goodsSpec.append(buyNumHtml);
				new Compute();
				}
				if(data.obj.content == undefined) {
					$("#goodsContext").html(" 无");
				}else {
					$("#goodsContext").html(data.obj.content);
				}
				goodsInfo.show();
			}
			if(data.result.state == 0 && data.result.message == "001"){
				layer.open({
				    content:"没有该商品",
				    time: 2
				});
				window.location.href =contextPath+"/";
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.open({
			    content:textStatus,
			    time: 2
			});
		}
	});		
}

$(document).on('click','.options_box_list .options_box_item',function(){
	$(this).closest('.options_box_list').find('.options_box_item').removeClass('options_box_item_active');
	$(this).addClass('options_box_item_active');
	var bidPrice = goodsSpecList[getSpec()].bid_price;
	var marketPrice = goodsSpecList[getSpec()].market_price;
	var price = goodsSpecList[getSpec()].price;
	var salesPrice = goodsSpecList[getSpec()].salesPrice;
	if(isPointsBuy == "01"){
		if(isSales == "00"){
			var changePoints = getReqPoints(bidPrice,marketPrice,price);
			var discount = toDecimal(bidPrice/marketPrice);
			var minRatio = ratioConfigure.min_ratio;
			var changePrice = 0;
			if(discount > minRatio){
				changePrice = (price-changePoints).toFixed(2);
			}
			if(changePrice == 0){
				$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券");
			}else{
				$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券 + <span class='money'>" + changePrice + "</span>元");
			}
			$(".sellPrice").html(price);
		}else{
			var changePoints = getReqPoints(bidPrice,marketPrice,salesPrice);
			var discount = toDecimal(bidPrice/marketPrice);
			var minRatio = ratioConfigure.min_ratio;
			var changePrice = 0;
			if(discount > minRatio){
				changePrice = (price-changePoints).toFixed(2);
			}
			if(changePrice == 0){
				$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券");
			}else{
				$(".rebate").html("<em class='npoints'>" + changePoints + "</em> 兑换券 + <span class='money'>" + changePrice + "</span>元");
			}
			$(".sellPrice").html(salesPrice);
		}
	}else{
		if(isSales == "00"){
			$(".normal").html("&yen; " + price);
		}else{
			$(".normal").html("&yen; " + salesPrice);
		}
	}
	
});

function nowBuy(){
	//封装参数
	var id =  $("#goodsId").attr("value");
	var amount = $(".quantity_input").val();

	var spec=getSpec();
	//跳转
	location.href=contextPath+'/pay/buy_now?goodsId='+id+'&spec='+spec+'&buyNum='+amount;
}

function getReqPoints(bidPrice, marketPrice, price){
	var changePoints = 0;
	var discount = toDecimal(bidPrice/marketPrice);
	var minRatio = ratioConfigure.minRatio;
	var maxRatio = ratioConfigure.maxRatio;
	if(discount<=minRatio){
		changePoints = Math.ceil(price);
	}else if(discount<=maxRatio){
		changePoints = parseInt(price*(1-discount/10)/(1-minRatio/10));
	}
	return changePoints;
}

function toDecimal(x) {    
    var f = parseFloat(x);    
    if (isNaN(f)) {    
        return;    
    }    
    f = Math.round(x*1000)/100;    
    return f;    
} 
